
//
//  HistoryViewController.m
//  Runone
//
//  Created by runone01 on 16/8/25.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "HistoryViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "Define.h"
#import "MJExtension.h"
#import "AllLastestVehicleDynamic.h"
#import "MovingAnnotationView.h"
#import "TracingPoint.h"
#import "Util.h"

@interface HistoryViewController ()<MAMapViewDelegate>
@property (nonatomic, strong) MAMapView *map;//地图
@property (nonatomic, strong) MAPointAnnotation * car;
@property (nonatomic, strong)AllLastestVehicleDynamic *model;
@end

@implementation HistoryViewController {
    NSMutableArray * _tracking;
    CFTimeInterval _duration;
}

#pragma     - ------历史轨迹


//NSArray *allPileArray = mydelegate.PirArray;
//for (HighwayMergeRoadRecordModel *roadModel in mydelegate.HighWayRoadArray) {
//    NSMutableArray *drawArray = [[NSMutableArray alloc] init];
//    for (PileInfo *model in allPileArray) {
//        if ([model.RoadUID isEqualToString:roadModel.RoadUID]) {     // 主干道
//            [drawArray addObject:model];}
//    }
//    MAMapPoint drawPoly[drawArray.count];
//    for (int i = 0;  i < drawArray.count; i++) {
//        PileInfo *model = drawArray[i];
//        drawPoly[i] = MAMapPointForCoordinate(CLLocationCoordinate2DMake(model.Latitude, model.Longitude));
//    }
//    MAPolyline *polyLine = [MAPolyline polylineWithPoints:drawPoly count:drawArray.count];
//    [_mapView addOverlay:polyLine];
//}


- (void)initRoute
{
    _duration = 10.0;
    MAMapPoint routePoly[_arr.count];
    
    for (int i =0; i < _arr.count; i++) {
        AllLastestVehicleDynamic *model = _arr[i];
        routePoly[i] = MAMapPointForCoordinate(CLLocationCoordinate2DMake(model.Latitude, model.Longitude));
    }
    MAPolyline *polyLine = [MAPolyline polylineWithPoints:routePoly count:_arr.count];
    [_map addOverlay:polyLine];

    
    //    [self.map showAnnotations:routeAnno animated:NO];
   
    
    NSUInteger count = self.arr.count;
    CLLocationCoordinate2D * coords = malloc(count * sizeof(CLLocationCoordinate2D));
    for (int i=0; i<count; i++) {
        _model=self.arr[i];
        
        coords[i] = CLLocationCoordinate2DMake(_model.Latitude,  _model.Longitude );
    }

    NSMutableArray * routeAnno = [NSMutableArray array];
    for (int i = 0 ; i < _arr.count; i++)
    {
        MAPointAnnotation * a = [[MAPointAnnotation alloc] init];
        a.coordinate = coords[i];
        a.title = @"route";
        [routeAnno addObject:a];
    }
//    [self.map showAnnotations:routeAnno animated:NO];
    [self.map showAnnotations:routeAnno edgePadding:UIEdgeInsetsMake(64, 10, 10, 10) animated:YES];
    [self initTrackingWithCoords:coords count:count];
    
    if (coords) {
        free(coords);
    }
    
}
//MAMapPoint drawPoly[drawArray.count];
//for (int i = 0;  i < drawArray.count; i++) {
//    PileInfo *model = drawArray[i];
//    drawPoly[i] = MAMapPointForCoordinate(CLLocationCoordinate2DMake(model.Latitude, model.Longitude));
//}
//MAPolyline *polyLine = [MAPolyline polylineWithPoints:drawPoly count:drawArray.count];
//[_mapView addOverlay:polyLine];


//开启定位
//- (void)showRouteForCoords:(CLLocationCoordinate2D *)coords count:(NSUInteger)count
//{
//    //show route
//    
//    MAPolyline *route = [MAPolyline polylineWithCoordinates:coords count:count];
//    [self.map addOverlay:route];
////    const CGFloat screenEdgeInset = 20;
////    UIEdgeInsets inset = UIEdgeInsetsMake(0, screenEdgeInset, screenEdgeInset, screenEdgeInset);
////    /* 使轨迹在地图可视范围内. */
////    [self.map setVisibleMapRect:route.boundingMapRect edgePadding:inset animated:NO];
//    
//    NSMutableArray * routeAnno = [NSMutableArray array];
//    for (int i = 0 ; i < count; i++)
//    {
//        MAPointAnnotation * a = [[MAPointAnnotation alloc] init];
//        a.coordinate = coords[i];
//        a.title = @"route";
//        [routeAnno addObject:a];
//    }
//    [self.map addAnnotations:routeAnno];
////    [self.map showAnnotations:routeAnno animated:NO];
//    [self.map showAnnotations:routeAnno edgePadding:UIEdgeInsetsMake(0 , 10, 0, 10) animated:YES];
//    
//}

- (void)initTrackingWithCoords:(CLLocationCoordinate2D *)coords count:(NSUInteger)count {
    _tracking = [NSMutableArray array];
    for (int i = 0; i<count - 1; i++)
    {
        TracingPoint * tp = [[TracingPoint alloc] init];
        tp.coordinate = coords[i];
        tp.course = [Util calculateCourseFromCoordinate:coords[i] to:coords[i+1]];
        [_tracking addObject:tp];
    }
    
    TracingPoint * tp = [[TracingPoint alloc] init];
    tp.coordinate = coords[count - 1];
    tp.course = ((TracingPoint *)[_tracking lastObject]).course;
    [_tracking addObject:tp];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *label     = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    label.text          = @"历史轨迹";
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor     = [UIColor whiteColor];
    self.navigationItem.titleView = label;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.view addSubview:self.map];
    [self initBtn];
    [self initAnnotation];
//    [self defaultAnnimation];
}

- (void)mov:(UIButton *)btn
{
    btn.selected=!btn.selected;
    if (btn.selected) {
        [btn setBackgroundImage:[UIImage imageNamed:@"map_stop_track"] forState:UIControlStateNormal];
    }
    else
    {
        [btn setBackgroundImage:[UIImage imageNamed:@"map_play_track"] forState:UIControlStateNormal];
    }
    [self.map removeAnnotation:_car];
    TracingPoint * start = [_tracking firstObject];
    MAPointAnnotation *car = [[MAPointAnnotation alloc] init];
    car.coordinate = start.coordinate;
    car.title = @"Car";
    _car=car;
    [self.map addAnnotation:_car];
    
    MovingAnnotationView * carView = (MovingAnnotationView *)[self.map viewForAnnotation:self.car];
    
    [carView addTrackingAnimationForPoints:_tracking duration:_duration];
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
        MovingAnnotationView *annotationView = (MovingAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MovingAnnotationView alloc] initWithAnnotation:annotation
                                                              reuseIdentifier:pointReuseIndetifier];
        }
        
        if ([annotation.title isEqualToString:@"Car"])
        {
            UIImage *imge  =  [UIImage imageNamed:@"map_car_track"];
            annotationView.image =  imge;
            CGPoint centerPoint=CGPointZero;
            [annotationView setCenterOffset:centerPoint];
        }
        else if ([annotation.title isEqualToString:@"route"])
        {
            annotationView.image = [UIImage imageNamed:@"trackingPoints.png"];
        }
        
        return annotationView;
    }
    
    return nil;
}


- (MAPolylineRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay {
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
        polylineRenderer.lineWidth   = 10.f;
        polylineRenderer.strokeColor = [UIColor redColor];
        
        return polylineRenderer;
    }
    return nil;
}

- (void)initAnnotation
{
    [self initRoute];
    
    /* Step 1. */
    //show car
    
    TracingPoint * start = [_tracking firstObject];
    self.car = [[MAPointAnnotation alloc] init];
    self.car.coordinate = start.coordinate;
    self.car.title = @"Car";
    [self.map addAnnotation:self.car];
    
}

- (MAMapView *)map {
    if (!_map) {
        _map = [[MAMapView alloc] initWithFrame:self.view.frame];
        [_map setDelegate:self];
        
        //加入annotation旋转动画后，暂未考虑地图旋转的情况。
        _map.rotateCameraEnabled = NO;
        _map.rotateEnabled = NO;
    }
    return _map;
}

- (void)initBtn {
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(30, self.view.frame.size.height/2+200, 34, 34);
    //btn.backgroundColor = [UIColor greenColor];
//    [btn setTitle:@"开始" forState:UIControlStateNormal];
    btn.backgroundColor=[UIColor clearColor];
    btn.tintColor=[UIColor clearColor];
    [btn addTarget:self action:@selector(mov:) forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundImage:[UIImage imageNamed:@"map_play_track"] forState:UIControlStateNormal];

    [self.view addSubview:btn];
}

-(void)defaultAnnimation { // 2016-12-17 14:57:09.901883 Runone[9060:720310] 0.172962--0.105757--12.855298--23.082255--113.356214
    NSInteger i = _arr.count/2;
    _model=_arr[i];
    MACoordinateSpan span = MACoordinateSpanMake(0.8, 0.8);
    CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(_model.Latitude,   _model.Longitude);
    MACoordinateRegion region = MACoordinateRegionMake(centerCoordinate, span);
    _map.region = region;
}

-(void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
//    NSLog(@"%f--%f--%f--%f--%f",mapView.region.span.latitudeDelta,mapView.region.span.longitudeDelta,mapView.zoomLevel,mapView.region.center.latitude,mapView.region.center.longitude);
}

//-(void)viewDidAppear:(BOOL)animated {
//    
//}



@end
